var Api = (function () {

    var ex = {}, api = {}, url = '', token = {
        'id': 0
    };

    ex.getUrl = function () {
        return url;
    };

    //----------------------

    ex.loadApi = function (apiData) {
        api = apiData;
        url = apiData.url;
        return ex;
    };

    ex.loadToken = function (t) {
        token = {
            'id': t.id,
            'token': t.token
        };
        return ex;
    };

    ex.setReady = function () {
        $.ajaxSetup({
            beforeSend: function (xhr) {
                xhr.setRequestHeader('X-App', 'chrome');
                if (token.id > 0) {
                    xhr.setRequestHeader('X-User', token.id);
                    xhr.setRequestHeader('X-Token', token.token);
                }
            }
        })
    };

    ex.request = function (name, data, success) {
        var apiData = api[name], option = {};
        option.url = url + 'api/' + apiData.url;
        option.dataType = 'json';
        option.data = data;
        var method = apiData.method.toUpperCase();
        if (method == 'DELETE' || method == 'PUT') {
            option.headers = {
                method: method
            };
            option.type = 'POST';
        } else {
            option.type = method;
        }
        option.success = success;
        $.ajax(option);
    };

    return ex;

}());

var Event = (function () {

    var event = {}, obj = $({});

    event.on = function () {
        obj.on.apply(obj, arguments);
    };

    event.off = function () {
        obj.off.apply(obj, arguments);
    };

    event.trigger = function () {
        console.log('[event] trigger : ' + arguments[0]);
        obj.trigger.apply(obj, arguments);
    };

    return event;

}());

var Background = (function () {

    var ex = {};

    var browserAction = {
        url: "login.html",
        startListen: function () {
            chrome.browserAction.onClicked.addListener(function () {
                chrome.tabs.query({
                    url: chrome.runtime.getURL(browserAction.url)
                }, function (tabs) {
                    if (tabs.length < 1) {
                        chrome.tabs.create({
                            url: chrome.runtime.getURL(browserAction.url)
                        })
                    } else {
                        chrome.tabs.update(tabs[0].id, {
                            active: true
                        });
                    }
                });
            });
        },
        setNonUser: function () {
            chrome.browserAction.setBadgeBackgroundColor({
                color: '#ffa14b'
            });
            chrome.browserAction.setTitle({
                title: '未登录 @傅小黑.ME'
            });
            chrome.browserAction.setBadgeText({
                text: ' '
            });
        },
        setAvailable: function () {
            chrome.browserAction.setBadgeBackgroundColor({
                color: '#69cd33'
            });
            chrome.browserAction.setTitle({
                title: '已登录 @傅小黑.ME'
            });
            chrome.browserAction.setBadgeText({
                text: ' '
            });
            this.url = 'app.html';
        },
        setError: function () {
            chrome.browserAction.setBadgeBackgroundColor({
                color: '#CC3300'
            });
            chrome.browserAction.setTitle({
                title: '网络错误 @傅小黑.ME'
            });
            chrome.browserAction.setBadgeText({
                text: ' '
            });
        }
    };

    var runtimeMessage = {
        startListen: function () {
            chrome.runtime.onMessage.addListener(function (data, sender) {
                if (data.event) {
                    Event.trigger(data.event, [data.data, sender.tab]);
                }
            });
        },
        startInternalEvent: function () {
            Event.on('internal.user.login', function (e, json, sender) {
                var url = json.url + 'api.json';
                $.ajax({
                    url: url,
                    dataType: 'json',
                    success: function (j) {
                        j.url = json.url;
                        localStorage.setItem('apiData', JSON.stringify(j));
                        Api.loadApi(j);
                        Api.setReady();
                        Api.request('user-authorize', json, function (json) {
                            if (json.response) {
                                Api.loadToken(json.user);
                                Api.setReady();
                                localStorage.setItem('userData', JSON.stringify(json.user));
                                browserAction.setAvailable();
                            }
                            runtimeMessage.send2Tab(sender.id, {
                                'event': 'internal.user.login.response',
                                'data': json
                            });
                        });
                    },
                    error: function (xhr) {
                        alert('API错误：' + xhr.statusCode + ',' + xhr.statusText);
                    }
                })
            });
        },
        startBlogEvent: function () {
            Event.on('editor.blog.save', function (e, data, sender) {
                var event = data.id > 0 ? 'blog-edit' : 'blog-create';
                Api.request(event, data.formData, function (json) {
                    chrome.tabs.sendMessage(sender.id, {
                        event: 'editor.blog.save.result',
                        data: json
                    });
                    if (json.response && json.blog.status == 'publish') {
                        var url = Api.getUrl() + 'post/' + json.blog.id + '.html';
                        chrome.tabs.create({
                            url: url
                        });
                    }
                });
            });
            Event.on('editor.category.get', function (e, data, sender) {
                Api.request('category-get', {all: true}, function (json) {
                    chrome.tabs.sendMessage(sender.id, {
                        event: 'editor.category.get.result',
                        data: json
                    })
                });
            });
            Event.on('editor.blog.get', function (e, data, sender) {
                Api.request('blog-get', {id: data.id}, function (json) {
                    chrome.tabs.sendMessage(sender.id, {
                        event: 'editor.blog.get.result',
                        data: json
                    })
                })
            });
        },
        startContentEvent: function () {
            Event.on('content.blog.change', function (e, data, sender) {
                Api.request('blog-edit', {
                    id: data.id,
                    status: data.status,
                    change: true
                }, function (json) {
                    chrome.tabs.sendMessage(sender.id, {
                        event: 'content.blog.change.result',
                        data: json
                    });
                });
            });
        },
        send2Tab: function (tabId, message) {
            chrome.tabs.sendMessage(tabId, message);
        },
        startEvent: function () {
            this.startInternalEvent();
            this.startBlogEvent();
            this.startContentEvent();
        }
    };

    var contentScript = {
        listenInjection: function () {
            chrome.tabs.onUpdated.addListener(function (id, changeInfo, tab) {
                if (changeInfo.status == 'loading') {
                    return;
                }
                if (tab.url.indexOf(Api.getUrl()) === 0 && browserAction.url == 'app.html') {
                    contentScript.doInjection(id);
                }
            });
        },
        doInjection: function (tabId) {
            chrome.tabs.insertCSS(tabId, {file: '/css/content.css'});
            chrome.tabs.executeScript(tabId, {file: '/lib/jquery-1.8.3.min.js'});
            chrome.tabs.executeScript(tabId, {file: '/lib/jquery.tools.min.js'});
            chrome.tabs.executeScript(tabId, {file: '/js/content.js'});
        }
    };

    function _checkUser(success, error) {
        Api.request('user-check', '', function (json) {
            if (json.response) {
                success();
            } else {
                error();
            }
        });
    }


    ex.start = function () {
        runtimeMessage.startListen();
        runtimeMessage.startEvent();
        contentScript.listenInjection();
        browserAction.startListen();
        browserAction.setError();
        var apiData = localStorage.getItem('apiData'),
            userData = localStorage.getItem('userData');
        if (!apiData || !userData) {
            browserAction.setNonUser();
            Api.setReady();
            return;
        }
        Api.loadApi(JSON.parse(apiData))
            .loadToken(JSON.parse(userData))
            .setReady();
        _checkUser(function () {
            browserAction.setAvailable();
        }, function () {
            browserAction.setNonUser();
        });
    };

    return ex;

}());

Background.start();